package com.desk.api.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.util.SaResult;
import com.desk.api.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExceptionHandel {

  // 全局异常拦截（拦截项目中的NotLoginException异常）
  @ExceptionHandler(NotLoginException.class)
  public SaResult handlerNotLoginException(NotLoginException nle) throws Exception {
    // 判断场景值，定制化异常信息
    String message = "";
    if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
      message = "未登录";
    } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
      message = "登录无效";
    } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
      message = "登录已过期";
    } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
      message = "已被顶下线";
    } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
      message = "已被踢下线";
    } else {
      message = "当前会话未登录";
    }
    // 返回给前端
    return SaResult.code(403).setMsg(message);
  }

  @ExceptionHandler(BusinessException.class)
  public SaResult handlerBusinessException(BusinessException e) {
    log.error(e.getMessage());
    return SaResult.error(e.getMessage());
  }

  @ExceptionHandler(Exception.class)
  public SaResult handlerException(Exception e) {
    log.error("系统异常:", e);
    return SaResult.error("当前访问人数过多，请稍后再试");
  }
}
